<template>
  <div class="student-container">
    <div class="header">
      <h2>学生信息管理系统</h2>
      <div>
        <el-button type="success" @click="showSearchDialog">查找学生</el-button>
        <el-button type="primary" @click="resetList">重置</el-button>
        <el-button type="primary" @click="showAddDialog">新增学生</el-button>
      </div>
    </div>

    <!-- 新增/修改学生弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      :title="isEditMode ? '修改学生信息' : '添加新学生'"
      width="50%"
    >
      <el-form :model="inputFormAdd" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号">
              <el-input
                v-model="inputFormAdd.studentId"
                placeholder="请输入学号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名">
              <el-input
                v-model="inputFormAdd.studentName"
                placeholder="请输入姓名"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select
                v-model="inputFormAdd.gender"
                placeholder="请选择性别"
                style="width: 100%"
              >
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期">
              <el-date-picker
                v-model="inputFormAdd.birthDate"
                type="date"
                placeholder="请选择出生日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入学日期">
              <el-date-picker
                v-model="inputFormAdd.enrollmentDate"
                type="date"
                placeholder="请选择入学日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学院">
              <el-input
                v-model="inputFormAdd.deptId"
                placeholder="请输入学院ID"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班级">
              <el-input
                v-model="inputFormAdd.classId"
                placeholder="请输入班级ID"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码">
              <el-input
                v-model="inputFormAdd.phone"
                placeholder="请输入手机号码"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电子邮箱">
              <el-input
                v-model="inputFormAdd.email"
                placeholder="请输入电子邮箱"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="家庭住址">
              <el-input
                v-model="inputFormAdd.address"
                placeholder="请输入家庭住址"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button
          @click="
            addDialogVisible = false;
            isEditMode = false;
          "
          >取消</el-button
        >
        <el-button v-if="isEditMode" type="primary" @click="update"
          >修改</el-button
        >
        <el-button v-else type="primary" @click="submit">提交</el-button>
      </template>
    </el-dialog>

    <!-- 查询学生弹窗 -->
    <el-dialog v-model="searchDialogVisible" title="查询学生" width="50%">
      <el-form :model="inputFormSearch" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号">
              <el-input
                v-model="inputFormSearch.studentId"
                placeholder="请输入学号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名">
              <el-input
                v-model="inputFormSearch.studentName"
                placeholder="请输入姓名"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select
                v-model="inputFormSearch.gender"
                placeholder="请选择性别"
                style="width: 100%"
              >
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期">
              <el-date-picker
                v-model="inputFormSearch.birthDate"
                type="date"
                placeholder="请选择出生日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入学日期">
              <el-date-picker
                v-model="inputFormSearch.enrollmentDate"
                type="date"
                placeholder="请选择入学日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学院">
              <el-input
                v-model="inputFormSearch.deptId"
                placeholder="请输入学院ID"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班级">
              <el-input
                v-model="inputFormSearch.classId"
                placeholder="请输入班级ID"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码">
              <el-input
                v-model="inputFormSearch.phone"
                placeholder="请输入手机号码"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电子邮箱">
              <el-input
                v-model="inputFormSearch.email"
                placeholder="请输入电子邮箱"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="家庭住址">
              <el-input
                v-model="inputFormSearch.address"
                placeholder="请输入家庭住址"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="searchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="search">查找</el-button>
      </template>
    </el-dialog>

    <!-- 学生信息表格 -->
    <div class="table-container">
      <div class="table-wrapper">
        <el-table :data="list" border stripe style="width: 100%; height: 70vh">
          <el-table-column
            v-for="(label, prop) in formPropMap"
            :key="prop"
            :prop="prop"
            :label="label"
          />
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button size="small" @click="handleUpdate(scope.row.studentId)"
                >编辑</el-button
              >
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row.studentId)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="params.pageNo"
            v-model:page-size="params.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <el-dialog v-model="dialogVisible" title="删除学生" width="30%">
      <span>确认要删除该学生吗？</span>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleDeleteConfirm"
          >确认删除</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { studentApi } from "../api";
import { ElMessage } from "element-plus";

type Gender = "男" | "女" | undefined;

type StudentForm = {
  studentId: string;
  studentName: string;
  gender: Gender;
  birthDate: string;
  enrollmentDate: string;
  deptId: string;
  classId: string;
  phone: string;
  email: string;
  address: string;
};

// 添加表单数据
const inputFormAdd = reactive<StudentForm>({
  studentId: "",
  studentName: "",
  gender: "男",
  birthDate: "",
  enrollmentDate: "",
  deptId: "",
  classId: "",
  phone: "",
  email: "",
  address: ""
});

// 查找表单数据
const inputFormSearch = reactive<StudentForm>({
  studentId: "",
  studentName: "",
  gender: undefined,
  birthDate: "",
  enrollmentDate: "",
  deptId: "",
  classId: "",
  phone: "",
  email: "",
  address: ""
});

// 新增弹窗显示状态
const addDialogVisible = ref(false);

// 查询弹窗显示状态
const searchDialogVisible = ref(false);

// 显示搜索弹窗
const showSearchDialog = () => {
  searchDialogVisible.value = true;
};

/**
 * 重置输入信息表格
 */
const resetForm = (form: StudentForm) => {
  Object.assign(form, {
    studentId: "",
    studentName: "",
    gender: undefined,
    birthDate: "",
    enrollmentDate: "",
    deptId: "",
    classId: "",
    phone: "",
    email: "",
    address: ""
  });
};

/**
 * 显示新增弹窗
 */
const showAddDialog = () => {
  // 清空表单
  resetForm(inputFormAdd);
  addDialogVisible.value = true;
};

/**
 * 属性名称映射表
 */
const formPropMap = ref({
  studentId: "学号",
  studentName: "姓名",
  gender: "性别",
  birthDate: "出生日期",
  enrollmentDate: "入学日期",
  deptId: "学院",
  classId: "班级",
  phone: "手机号码",
  email: "电子邮箱",
  address: "家庭地址"
});

// 分页相关
interface PageParams {
  pageNo: number;
  pageSize: number;
}

// 表格
const list = ref<StudentForm[]>([]);
// 数据总数
const total = ref(0);
// 分页请求参数
const params = ref<PageParams>({
  pageNo: 1,
  pageSize: 10
});

// 提交表单
const submit = async () => {
  try {
    await studentApi.create(inputFormAdd);
    ElMessage.success("创建学生成功");
    addDialogVisible.value = false;
    getList(); // 刷新列表
  } catch (error) {
    ElMessage.error("创建学生失败");
    console.error("创建学生失败", error);
  }
};

/**
 * 根据搜索条件获取搜索结果
 */
const getList = async () => {
  try {
    const res = await studentApi.getPage(inputFormSearch, {
      page: params.value.pageNo - 1,
      size: params.value.pageSize
    });

    // ElMessage.success('查询成功');
    searchDialogVisible.value = false;
    list.value = res.data.content || [];
    total.value = res.data.totalElements || 0;
  } catch (error) {
    ElMessage.error("查询失败");
    console.error("查询学生信息失败", error);
    list.value = [];
    total.value = 0;
  }
};

/**
 * 处理条件搜索
 */
const search = () => {
  // 重置到第一页
  params.value.pageNo = 1;
  // 刷新
  getList();
};

// 删除相关逻辑
const dialogVisible = ref(false);
const toDeleteId = ref("");

/**
 * 打开删除弹窗
 * @param id 需要删除的学生id
 */
const handleDelete = (id: string) => {
  dialogVisible.value = true;
  toDeleteId.value = id;
};

/**
 * 处理确认删除学生功能
 */
const handleDeleteConfirm = async () => {
  try {
    await studentApi.delete(toDeleteId.value);
    ElMessage.success("删除成功");
    dialogVisible.value = false;
    getList(); // 刷新列表
  } catch (error) {
    ElMessage.error("删除失败");
    console.error("删除学生失败:", error);
  }
};

/**
 * 处理分页数变化
 * @param val 分页数
 */
const handleSizeChange = (val: number) => {
  params.value.pageSize = val;
  params.value.pageNo = 1;
  getList();
};

/**
 * 处理页号变化
 * @param val 页号
 */
const handleCurrentChange = (val: number) => {
  params.value.pageNo = val;
  getList();
};

// 编辑学生信息模式
const isEditMode = ref(false);
const editId = ref<string>("");

/**
 * 打开学生信息编辑窗口
 * @param id 学生id
 */
const handleUpdate = async (id: string) => {
  try {
    // 进入编辑模式
    isEditMode.value = true;
    // 更新正在编辑的学生id
    editId.value = id;
    // 获取该生信息
    const student = await studentApi.getById(id);
    // 将该生信息填入修改表单
    Object.assign(inputFormAdd, student.data);
    // 打开编辑弹窗
    addDialogVisible.value = true;
  } catch (error) {
    ElMessage.error("获取学生信息失败");
    console.error("获取学生信息失败:", error);
  }
};

/**
 * 更新学生信息
 */
const update = async () => {
  try {
    // 更新学生信息
    await studentApi.update(editId.value, inputFormAdd);
    ElMessage.success("学生更新成功");
    // 关闭编辑模式
    isEditMode.value = false;
    // 关闭编辑窗口
    addDialogVisible.value = false;
    // 刷新表格
    getList();
  } catch (error) {
    ElMessage.error("更新学生信息失败");
    console.error("更新学生信息失败:", error);
  }
};

/**
 * 重置表格，取消带搜索条件的获取表格
 */
const resetList = () => {
  resetForm(inputFormSearch);
  ElMessage.success("重置表格成功");
  // 重置到第一页
  params.value.pageNo = 1;
  getList();
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.student-container {
  // padding: 20px;
  background-color: #f5f7fa;
  // min-height: 100vh;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  // height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-shrink: 0;

  h2 {
    margin: 0;
    color: #303133;
  }
}

.table-container {
  flex: 1;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  min-height: 0;
  // overflow-y: auto;
}

.table-wrapper {
  flex: 1;
  // flex-shrink: 0;
  overflow-y: auto;
}

.pagination {
  flex-shrink: 0;
  background: white;
  padding: 10px 0;
}
</style>
